<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单号" prop="bizOrderNo">
        <el-input
          v-model="queryParams.bizOrderNo"
          placeholder="请输入订单号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="老人姓名" prop="serviceElderName">
        <el-input
          v-model="queryParams.serviceElderName"
          placeholder="请输入老人姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户姓名" prop="customerName">
        <el-input
          v-model="queryParams.customerName"
          placeholder="请输入客户姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="createdAt">
        <el-date-picker clearable
          v-model="queryParams.createdAt"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择创建时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    
    <!-- 状态筛选按钮组 -->
    <div class="status-filter-area">
      <el-row :gutter="10" align="middle">
        <el-col>
          <el-button
            v-for="item in statusOptions"
            :key="item.value"
            :type="currentStatus === item.value ? 'primary' : 'default'"
            size="mini"
            class="status-btn"
            @click="handleStatusFilter(item.value)"
          >
            {{ item.label }}
          </el-button>
        </el-col>
      </el-row>
    </div>

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" >
      <template #default="scope">
         <!-- 计算逻辑：(当前页-1)*每页条数 + 当前页索引 + 1 -->
        {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="订单号" align="center" prop="bizOrderNo" />
      <!-- <el-table-column label="老人ID" align="center" prop="serviceElderId" /> -->
      <el-table-column label="老人姓名" align="center" prop="serviceElderName" />
      <el-table-column label="床位号" align="center" prop="extend1" />
      <!-- <el-table-column label="服务项目id" align="center" prop="serviceItemId" /> -->
      <el-table-column label="服务项目" align="center" prop="serviceItemName" />
      <el-table-column label="订单金额(元)" align="center" prop="amount" />
      <el-table-column label="预计服务时间" align="center" prop="expectedServiceTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.expectedServiceTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="客户id" align="center" prop="customerId" /> -->
      <el-table-column label="下单人" align="center" prop="customerName" />
      <el-table-column label="创建时间" align="center" prop="createdAt" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      
      <!-- 改造1：订单状态（标签化显示） -->
      <el-table-column label="订单状态" align="center" prop="orderStatus">
        <template #default="scope">
          <el-tag :type="getOrderStatusTagType(scope.row.orderStatus)">
            {{ getOrderStatusLabel(scope.row.orderStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      
      <!-- 改造2：交易状态（标签化显示） -->
      <el-table-column label="交易状态" align="center" prop="payStatus">
        <template #default="scope">
          <el-tag :type="getPayStatusTagType(scope.row.payStatus)">
            {{ getPayStatusLabel(scope.row.payStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      
      <!-- 改造3：操作列（三个按钮+状态控制） -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <!-- 取消按钮 -->
          <el-button 
            link 
            type="primary" 
            icon="Delete" 
            :disabled="!canCancel(scope.row.orderStatus, scope.row.payStatus)"
            :class="!canCancel(scope.row.orderStatus, scope.row.payStatus) ? 'btn-disabled' : ''"
            @click="handleCancel(scope.row)" 
            v-hasPermi="['greenold-order:order:cancel']"
          >取消</el-button>
          
          <!-- 退款按钮 -->
          <el-button 
            link 
            type="primary" 
            icon="Refresh" 
            :disabled="!canRefund(scope.row.orderStatus, scope.row.payStatus, scope.row.hasRefund)"
            :class="!canRefund(scope.row.orderStatus, scope.row.payStatus, scope.row.hasRefund) ? 'btn-disabled' : ''"
            @click="handleRefund(scope.row)" 
            v-hasPermi="['greenold-order:order:refund']"
          >退款</el-button>
          
          <!-- 查看按钮 -->
          <el-button 
            link 
            type="primary" 
            icon="Eye" 
            :disabled="!canView(scope.row.orderStatus)"
            :class="!canView(scope.row.orderStatus) ? 'btn-disabled' : ''"
            @click="handleView(scope.row.id)" 
            v-hasPermi="['greenold-order:order:view']"
          >查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

  <!-- 取消订单弹框 -->
    <el-dialog
      title="填写取消原因"
      v-model="cancelDialogVisible"
      width="400px"
      :before-close="() => (cancelDialogVisible = false)"
    >
      <el-form :model="cancelForm" ref="cancelFormRef" :rules="cancelRules" label-width="100px">
        <el-form-item label="取消原因" prop="cancelReason">
          <el-select 
            v-model="cancelForm.cancelReason" 
            placeholder="请选择取消原因" 
            clearable
          >
            <el-option
              v-for="item in cancelReasonOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmCancel">确定</el-button>
        </span>
      </template>
    </el-dialog>


<!-- 退款订单弹框 -->
    <el-dialog
      title="申请退款"
      v-model="refundDialogVisible"
      width="400px"
      :before-close="() => (refundDialogVisible = false)"
    >
      <el-form :model="refundForm" ref="refundFormRef" :rules="refundRules" label-width="100px">
                                                              <!-- 动态控制是否显示必填星号 -->
        <el-form-item label="退款原因" prop="refundReason" :required="isExecutedOrder">
          <el-input
            v-model="refundForm.refundReason"
            type="textarea"
            placeholder="请输入退款原因（限100字，不允许表情）"
            maxlength="100"
            show-word-limit
            :disabled="!isExecutedOrder" 
          />
          <!-- :disabled="!isExecutedOrder"  待执行时禁用输入 -->
           <div v-if="!isExecutedOrder" class="tips-text">待执行订单无需填写退款原因</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="refundDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmRefund">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Order">
import { ref, reactive,watch, computed} from 'vue';
import { listOrder, getOrder, delOrder, cancelOrder,addOrder, updateOrder ,refundOrder,listAll} from "@/api/greenold-order/order";
import { getCurrentInstance } from 'vue';
import { useRouter } from 'vue-router'; // 新增：引入路由钩子
const { proxy } = getCurrentInstance();
import { ElMessage } from 'element-plus';


const router = useRouter();// 初始化路由实例
// 订单列表数据
const orderList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

// 状态筛选相关
const currentStatus = ref(0); // 0=全部
const statusOptions = [
  { label: '全部', value: 0 },
  { label: '待支付', value: 1 },
  { label: '已支付', value: 2 },
  { label: '已取消', value: 3 },
  { label: '已退款', value: 4 },
];
/** 状态筛选处理：按钮点击后筛选表格数据 */
const handleStatusFilter = (btnValue) => {
  currentStatus.value = btnValue; // 记录当前选中按钮（用于高亮）
  
  // 重置筛选条件
  queryParams.value.orderStatus = null;
  queryParams.value.payStatus = null;
  
  // 根据按钮值设置组合筛选条件
  switch (btnValue) {
    case 1: // 待支付：订单状态=0 且 交易状态=0
      queryParams.value.orderStatus = "0";
      queryParams.value.payStatus = "0";
      break;
    case 2: // 已支付：订单状态为1/2/3 且 交易状态=1
      queryParams.value.orderStatus = "1,2,3";
      queryParams.value.payStatus = "1";
      break;
    case 3: // 已取消：订单状态=4 且 交易状态=2
      queryParams.value.orderStatus = "4";
      queryParams.value.payStatus = "2";
      break;
    case 4: // 已退款：交易状态=4
      queryParams.value.payStatus = "4";
      break;
    default: // 全部：不设置筛选条件
      queryParams.value.orderStatus = null;
      queryParams.value.payStatus = null;
  }
  
  queryParams.value.pageNum = 1; // 筛选后重置为第1页
  getList(); // 重新查询订单
};

/** 查询订单列表 */
function getList() {
  loading.value = true;
  listAll(queryParams.value).then(response => {
    // 订单按ID升序排序（可选）
    const sortedRows = response.rows.sort((a, b) => Number(a.id) - Number(b.id));
    orderList.value = sortedRows;
    total.value = response.total;
    loading.value = false;
  }).catch(() => {
    loading.value = false;
    ElMessage.error('订单列表加载失败');
  });
}


// 表单数据
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    bizOrderNo: null,
    serviceElderId: null,
    customerId: null,
    //新增加的老人姓名和客人姓名（用于搜索）
    serviceElderName: null,
    customerName: null,
    createdAt: null,
    createdBy:null,
    status: 0 ,// 状态筛选参数
    orderStatus: null, // 新增：订单状态筛选
    payStatus: null  // 新增：交易状态筛选

  },
  rules: {}
});

const { queryParams, form, rules } = toRefs(data);






// ========== 状态映射配置（根据实际业务调整） ==========
// 订单状态映射：键为orderStatus值，值为显示文本和标签类型
const orderStatusMap = reactive({
  0: { label: '待支付', type: 'warning' },
  1: { label: '待执行', type: 'success' },
  2: { label: '已执行', type: 'danger' },
  3: { label: '已完成', type: 'info' },
  4: { label: '已关闭', type: 'primary' },
  5: { label: '已退款', type: 'info' },
});

// 交易状态映射：键为payStatus值   (下面有这个是为了与订单看起来更方便)
// const payStatusMap = reactive({
//   0: { label: '待支付', type: 'warning' },
//   1: { label: '已支付', type: 'success' },
//   2: { label: '已关闭', type: 'danger' },
//   3: { label: '退款失败', type: 'warning' },
//   4: { label: '退款成功', type: 'danger' },
// });


// 取消订单弹框
const cancelDialogVisible = ref(false);
const cancelForm = reactive({
  cancelReason: '' // 绑定取消原因
});
const cancelFormRef = ref(null);
const cancelReasonOptions = [
  { label: '不需要此项服务了', value: '不需要此项服务了' },
  { label: '费用有点贵', value: '费用有点贵' },
  { label: '临时有事，不方便服务', value: '临时有事，不方便服务' },
  { label: '信息填写错误', value: '信息填写错误' },
  { label: '重复下单', value: '重复下单' }
];
const cancelRules = {
  cancelReason: [{ required: true, message: '请选择取消原因', trigger: 'change' }]
};


// ========== 核心状态定义 ==========
// 当前操作的订单（存储订单状态用于判断）
const currentOrder = ref({});
// 退款弹框显隐
const refundDialogVisible = ref(false);
// 退款表单数据
const refundForm = reactive({
  refundReason: '' // 退款原因
});
// 退款表单引用（用于验证）
const refundFormRef = ref(null);
// 是否为“已执行”订单（computed属性：根据currentOrder.orderStatus判断）
const isExecutedOrder = computed(() => {
  // 订单状态：1=待执行，2=已执行（与业务状态保持一致）
 console.log(currentOrder.value.orderStatus);
  return currentOrder.value.orderStatus === "2";
});

// ========== 动态退款验证规则 ==========
// 初始规则（默认非必填）
const refundRules = ref({
  refundReason: [
    { max: 100, message: '最多输入100个字符', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        // 禁止表情校验（通用）
        const emojiReg = /[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]]+|[^\u0020-\uFFFF]/g;
       emojiReg.test(value) ? callback(new Error('不允许输入表情')) : callback();
      },
      trigger: 'blur'
    }
  ]
});


// 监听“是否已执行订单”变化，动态添加/移除必填规则
watch(isExecutedOrder, (isExecuted) => {
  if (isExecuted) {
    // 已执行订单：添加“必填”规则
    refundRules.value.refundReason.unshift({ 
      required: true, 
      message: '已执行订单需填写退款原因', 
      trigger: 'blur' 
    });
  } else {
    // 待执行订单：移除“必填”规则（保留其他校验）
    refundRules.value.refundReason = refundRules.value.refundReason.filter(
      rule => !rule.required
    );
  }

});




// ========== 退款按钮点击事件（打开弹框） ==========
// 退款订单方法
const handleRefund = (row) => {
   console.log('退款时的订单数据：', row); // 看row里有没有orderStatus
  currentOrder.value = row;
  refundDialogVisible.value = true;
  refundForm.refundReason = ''; // 重置输入
};

// ========== 确认退款（核心：动态验证） ==========
const confirmRefund = () => {
   refundFormRef.value.validate((valid) => {
    if (valid) {
      refundOrder({
        orderId: currentOrder.value.id,
        extend2: isExecutedOrder.value ? refundForm.refundReason : '', // 动态传参
        orderStatus: currentOrder.value.orderStatus ,// 传递订单状态给后端
        customerName: currentOrder.value.customerName // 传递客户姓名给后端
      }).then(res => {
        if (res.code === 200) {
          ElMessage.success('退款申请提交成功');
          refundDialogVisible.value = false;
          getList();
        } else {
          ElMessage.error(res.msg || '退款申请提交失败');
        }
      }).catch(() => ElMessage.error('退款申请提交异常'));
    }
  });


  // refundFormRef.value.validate((valid) => {
  //   if (valid) {
  //     refundOrder({
  //       orderId: currentOrder.value.id,
  //       refundReason: refundForm.refundReason
  //     }).then(res => {
  //       if (res.code === 200) {
  //         ElMessage.success('退款申请提交成功');
  //         refundDialogVisible.value = false;
  //         getList(); // 刷新列表
  //       } else {
  //         ElMessage.error(res.msg || '退款申请提交失败');
  //       }
  //     }).catch(() => ElMessage.error('退款申请提交异常'));
  //   }
  // });

};








// // 退款订单弹框
// const refundDialogVisible = ref(false);








// const refundForm = reactive({
//   refundReason: '' // 绑定退款原因
// });
// const refundFormRef = ref(null);
// const refundRules = {
//   refundReason: [
//     { required: true, message: '请输入退款原因', trigger: 'blur' },
//     { max: 100, message: '最多输入100个字符', trigger: 'blur' },
//     { 
//       validator: (rule, value, callback) => {
//         // 简单校验：禁止表情（实际可更精确）
//         const emojiReg = /[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]]+|[^\u0020-\uFFFF]/g;
//         if (emojiReg.test(value)) {
//           callback(new Error('不允许输入表情'));
//         } else {
//           callback();
//         }
//       },
//       trigger: 'blur'
//     }
//   ]
  
// };











// // 当前操作的订单
// const currentOrder = ref({});



// 交易状态映射：键为payStatus值
const payStatusMap = reactive({
  0: { label: '待支付', type: 'warning' },
  1: { label: '已支付', type: 'success' },
  2: { label: '已关闭', type: 'danger' },
  3: { label: '退款失败', type: 'warning' },
  4: { label: '退款成功', type: 'danger' },
});

// ========== 状态标签渲染函数 ==========
// 获取订单状态文本
const getOrderStatusLabel = (status) => {
  return orderStatusMap[status]?.label || '未知状态';
};

// 获取订单状态标签类型
const getOrderStatusTagType = (status) => {
  return orderStatusMap[status]?.type || 'default';
};

// 获取交易状态文本
const getPayStatusLabel = (status) => {
  return payStatusMap[status]?.label || '未知状态';
};

// 获取交易状态标签类型
const getPayStatusTagType = (status) => {
  return payStatusMap[status]?.type || 'default';
};

// ========== 操作按钮权限判断（核心逻辑） ==========
// 取消按钮：仅待支付状态可点击（根据实际业务调整条件）
const canCancel = (orderStatus, payStatus) => {
  // console.log('取消按钮权限判断：', orderStatus, payStatus);
  // 示例：订单状态为待支付（0）且交易状态为待支付（1）
  return orderStatus === "0" && payStatus === "0";
  //   const result = orderStatus === 0 && payStatus === 1;
  //   console.log('canCancel 返回值:', result);
  // return result;
};

// 退款按钮：
const canRefund = (orderStatus, payStatus, hasRefund) => {
  // console.log('退款按钮权限判断：', orderStatus, payStatus, hasRefund);
  return orderStatus === "1" && payStatus === "1" && hasRefund === 0||orderStatus === "2" && payStatus === "1" && hasRefund === 0;
  //    console.log('===== 退款按钮逻辑验证 =====');
  // console.log('orderStatus:', orderStatus, '类型:', typeof orderStatus);
  // console.log('payStatus:', payStatus, '类型:', typeof payStatus);
  // console.log('hasRefund:', hasRefund, '类型:', typeof hasRefund);
  // const result = orderStatus === "3" && payStatus === "2" && hasRefund === 0;
  // console.log('canRefund 返回值:', result);
  // return result;
};

// 查看按钮：所有状态均可点击
const canView = (orderStatus) => {
  return true; // 始终可点击
};

// ========== 按钮点击事件 ==========
// 取消订单
const handleCancel = (row) => {
  console.log(row.orderStatus,row.payStatus);
    currentOrder.value = row;
  cancelDialogVisible.value = true;
};

// 确认取消订单
const confirmCancel = () => {
  cancelFormRef.value.validate((valid) => {
    if (valid) {
      cancelOrder({
        orderId: currentOrder.value.id,
        cancelReason: cancelForm.cancelReason
      }).then(res => {
        if (res.code === 200) {
          ElMessage.success('取消订单成功');
          cancelDialogVisible.value = false;
          getList(); // 刷新列表
        } else {
          ElMessage.error(res.msg || '取消订单失败');
        }
      }).catch(() => ElMessage.error('取消订单异常'));
    }
  });
};





// 查看详情
const handleView = (id) => {
  if(id){
  router.push({ path: '/order/orderdetails', query: { id } });
  }
  // // 打开详情页逻辑
  // console.log('查看订单详情：', row.id);
  // // 示例：可以打开弹窗或路由跳转
  // // open.value = true;
  // // title.value = "订单详情";
  // // form.value = { ...row };
};

// ========== 原有列表功能逻辑 ==========






/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = {
    id: null,
    bizOrderNo: null,
    serviceElderId: null,
    extend1: null,
    serviceItemId: null,
    amount: null,
    expectedServiceTime: null,
    customerId: null,
    createdAt: null,
    orderStatus: null,// 新增：订单状态筛选
    payStatus: null,// 新增：交易状态筛选
    hasRefund: null,
    tradeOrderNo: null,
    refundAmount: null,
    cancelReason: null,
    updatedAt: null,
    createdBy: null,
    updatedBy: null,
    visible: null,
    cancelByType: null,
    remark: null,
    extend2: null

  };
  proxy.resetForm("orderRef");
}

// 初始化加载数据
getList();
</script>

<style scoped>
.status-filter-area {
  margin-bottom: 16px;
  padding-left: 10px;
}

.status-btn {
  min-width: 80px;
  border-radius: 4px;
  font-size: 12px;
  margin-right: 4px;
}

/* 禁用按钮样式：灰色不可点击 */
.btn-disabled {
  color: #c0c4cc !important;
  cursor: not-allowed !important;
  text-decoration: none !important;
}

/* 按钮间距 */
:deep(.el-button) {
  margin-right: 5px;
}
</style>
